package com.xrath.rtm;

import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.TimeZone;

/**
 * All RTM dates has UTC format. 
 * This class help that create a utility class to parse from UTC to java.util.Date object.
 *
 * @author Jang-Ho Hwang, rath@xrath.com
 * @version 1.0, since 2008/06/01
 */
class DateFormatter
{
	private SimpleDateFormat fmtDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

	public DateFormatter()
	{
		fmtDate.setTimeZone( TimeZone.getTimeZone("GMT") );
	}

	/**
	 *
	 * @param target - target object. (ex. Task)
	 * @param field - added, modified, created...
	 * @param strDate - empty string or UTC date (2008-03-01T17:00:04Z)
	 */
	public void set( Object target, String field, String strDate ) throws ParseException
	{
		if( strDate==null || strDate.trim().length()==0 )
			return;

		if( field.length()==0 )
			throw new IllegalArgumentException("field's length must greater than 1");

		Method method = null;
		try {
			method = target.getClass().getDeclaredMethod(
				"set" + field.substring(0,1).toUpperCase() + field.substring(1),
				Date.class);
		} catch( NoSuchMethodException e ) {
			// no happens.
			throw new RuntimeException(e);
		}

		Date date = fmtDate.parse(strDate);
		try {
			method.invoke(target, date);
		} catch( IllegalAccessException e ) {

		} catch( InvocationTargetException e ) {
			throw new RuntimeException(e.getCause());
		}
	}

	public String format( Date date )
	{
		return fmtDate.format(date);
	}
}
